package com.fuzhixuan.cloud.controller;

import com.fuzhixuan.cloud.entities.CommonResult;
import com.fuzhixuan.cloud.mybalancerload.MyLB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class PaymentZKController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private MyLB myLB;

    private final String URL = "http://cloud-provider-payment";

    @GetMapping(value = "/getServerPort")
    public String getServerPort() {
        return restTemplate.getForObject(URL + "/getServerPort", String.class);
    }

    @GetMapping(value = "/getById")
    public CommonResult getById(Integer id) {
        ResponseEntity responseEntity = restTemplate.getForEntity(URL + "/payment/getById?id=" + id, CommonResult.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            return CommonResult.ok(200, responseEntity.getBody());
        } else {
            return CommonResult.fail(444, "服务异常");
        }
    }

    @GetMapping(value = "/getServerPort/lb")
    public String getByIdLB() {
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("cloud-provider-payment");
        URI url = myLB.getServiceInstance(serviceInstanceList).getUri();
        return restTemplate.getForObject(url + "/getServerPort", String.class);
    }

}
